package com.tdkj.service.user.impl;

import java.sql.Timestamp;

import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.tdkj.model.common.BeanIpAddressInfo;
import com.tdkj.model.user.BeanUser;
import com.tdkj.model.user.BeanUserLoginLog;
import com.tdkj.service.BaseService;
import com.tdkj.service.user.IBeanUserLoginLogService;

@Component
public class BeanUserLoginLogServiceImpl extends BaseService implements IBeanUserLoginLogService {

	@Override
	public BeanUserLoginLog createLoginLog(Long userId, String ip) {
		String[] temps = ip.indexOf(":") == -1 ? ip.split("[.]") : ip.split("[:]");
		Long ipNum = Long.parseLong(temps[0]) * 256 * 256 * 256 + Long.parseLong(temps[1]) * 256 * 256 + Long.parseLong(temps[2]) * 256 + Long.parseLong(temps[3]);
		String hql = " from " + BeanIpAddressInfo.class.getName() + " as bean where bean.startIpNum<='" + ipNum + "' and bean.endIpNum>='" + ipNum + "'";
		Query query = this.getBaseDao().getSession().createQuery(hql);
		BeanIpAddressInfo info = (BeanIpAddressInfo) query.uniqueResult();

		BeanUser user = this.getBaseDao().findById(userId, BeanUser.class);

		BeanUserLoginLog bean = new BeanUserLoginLog();
		bean.setUser(user);
		bean.setIp(ip);
		if (null != info && null != info.getCountry())
			bean.setLocal(info.getCountry());
		bean.setLoginTime(new Timestamp(System.currentTimeMillis()));

		this.getBaseDao().save(bean);

		return bean;
	}

	@Override
	public void createLogoutLog(Long id) {
		BeanUserLoginLog bean = this.getBaseDao().findById(id, BeanUserLoginLog.class);
		bean.setLogoutTime(new Timestamp(System.currentTimeMillis()));
	}

	@Override
	public BeanUserLoginLog getLastLoginLog(Long userId) {
		String hql = "from " + BeanUserLoginLog.class.getName() + " as bean where bean.user.id='" + userId + "' order by bean.loginTime desc";
		BeanUserLoginLog bean = (BeanUserLoginLog) this.getBaseDao().getSession().createQuery(hql).setMaxResults(1).uniqueResult();
		return bean;
	}

}
